/*
 * @author: wizardc
 */

using UnityEngine;
using UnityEngine.UI;

namespace Dou.ScreenController
{
    /// <summary>
    /// CanvasScaler 支持横竖屏切换的适配器
    /// </summary>
    [RequireComponent(typeof(CanvasScaler))]
    public class CanvasScalerAdapter : MonoBehaviour, IUIAdapter
    {
        private CanvasScaler _canvasScaler;

        void Awake()
        {
            _canvasScaler = GetComponent<CanvasScaler>();
            ScreenUIAdapterMgr.instance.AddAdapter(this);
        }

        public void RefreshAdapter(int uiScreenMode, int uiFineTuningMode)
        {
            var screenMgr = ScreenManager.instance;
            var adapterMgr = ScreenUIAdapterMgr.instance;
            
            _canvasScaler.referenceResolution = screenMgr.isLandscape ? adapterMgr.landscapeDesignResolution : adapterMgr.portraitDesignResolution;
            if (_canvasScaler.screenMatchMode == CanvasScaler.ScreenMatchMode.MatchWidthOrHeight)
            {
                _canvasScaler.matchWidthOrHeight = screenMgr.isLandscape ? adapterMgr.landscapeMatchWidthOrHeight : 1f - adapterMgr.landscapeMatchWidthOrHeight;
            }
        }

#if UNITY_EDITOR

        public void RefreshAdapterInEditor(Vector2 referenceResolution, float matchWidthOrHeight)
        {
            var canvasScaler = GetComponent<CanvasScaler>();
            canvasScaler.referenceResolution = referenceResolution;
            canvasScaler.matchWidthOrHeight = matchWidthOrHeight;
        }
        
#endif
        
        void OnDestroy()
        {
            ScreenUIAdapterMgr.instance.RemoveAdapter(this);
        }
    }
}
